#include "gtest/gtest.h"

#include "Log.h"
#include "Topic.h"

#include "recovery/fs/file/File.h"

//TODO: think more case ????

TEST(LogSizeTest, testMain){
    Topic topic("stream-trans-meta", ".");
    Meta meta(topic);

	ASSERT_TRUE(meta.open());

    ASSERT_EQ(0ull, meta.logSize().value());

    meta.logSize().value(64ull);
    ASSERT_EQ(64ull, meta.logSize().value());
    ASSERT_TRUE(meta.sync());

    //load it
    meta.logSize().value(71ull);
    ASSERT_EQ(71ull, meta.logSize().value());
    meta.load();
    ASSERT_EQ(64ull, meta.logSize().value());


    //overwrite 
    ASSERT_TRUE(meta.logSize().overwrite(1024).sync());
	ASSERT_EQ(1024ull, meta.logSize().value());
    
    ASSERT_TRUE(meta.logSize().advance(128ull).sync());
    ASSERT_EQ(128ull+1024ull, meta.logSize().value());



	ASSERT_TRUE(meta.close());
}
TEST(MetaTest, testFirstLoad){


    Topic topic("stream-trans-meta-load", ".");
    Meta meta(topic);

	ASSERT_TRUE(meta.open());

    ASSERT_TRUE(meta.load());

	ASSERT_TRUE(meta.close());

    recovery::fs::file::File  f(topic.metaPath());
    ASSERT_TRUE(f.remove());
    ASSERT_TRUE(false == f.exist());
}


TEST(MetaTest, testMain){
    Topic topic("stream-trans-meta", ".");
    Meta meta(topic);

    ASSERT_TRUE(meta.open());

    ASSERT_EQ(0ull, meta.logSize().value());

    ASSERT_FALSE(meta.isSync());
    ASSERT_TRUE(meta.load());
    ASSERT_TRUE(meta.isSync());

    ASSERT_TRUE(meta.logSize().overwrite(64ull).sync());
    ASSERT_EQ(64ull, meta.logSize().value());

    ASSERT_TRUE(meta.logSize().advance(128ull).sync()); // write it 
    ASSERT_EQ(64ull+128ull, meta.logSize().value());

	// reset , and load it 
	ASSERT_TRUE(meta.reset());
    ASSERT_TRUE(meta.isSync());
    ASSERT_EQ(0ull, meta.logSize().value());

    ASSERT_TRUE(meta.load());
    ASSERT_EQ(0ull, meta.logSize().value());

	meta.logSize().value(100);
	ASSERT_TRUE(false == meta.isSync());

    ASSERT_TRUE(meta.sync());
    ASSERT_TRUE(meta.isSync());

    ASSERT_TRUE(meta.close());
}

TEST(LogTest, testMain){
    Topic topic("stream-trans-log", ".");
    Log log(topic);

    ASSERT_TRUE(log.open());

    size_t size = 0;
    ASSERT_TRUE(log.append("hello world", size));
    ASSERT_EQ(0x0bull + 8 + 8 + 4, size);
    ASSERT_TRUE(log.sync());

    ASSERT_TRUE(log.truncate(0));

    size = 0;
    ASSERT_TRUE(log.size(size));
    ASSERT_EQ(0ull, size);

    ASSERT_TRUE(log.close());
}

